package com.wb.mas.ui.auth;

import android.app.Application;
import android.net.Uri;
import android.text.TextUtils;

import com.blankj.utilcode.util.SPUtils;
import com.wb.mas.R;
import com.wb.mas.app.Constants;
import com.wb.mas.app.DictInfoTypeKey;
import com.wb.mas.app.SPKeys;
import com.wb.mas.app.UUidUtils;
import com.wb.mas.data.DemoRepository;
import com.wb.mas.entity.AuthBackResponse;
import com.wb.mas.entity.DicInfoEntity;
import com.wb.mas.entity.DicInfoResponse;
import com.wb.mas.entity.IdentityInfoResponse;
import com.wb.mas.entity.ImageInfoEntity;
import com.wb.mas.entity.RootApiBean;
import com.wb.mas.entity.SubmitedAuthResponse;
import com.wb.mas.entity.UploadImageResponse;
import com.wb.mas.utils.response.ResultException;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent;
import me.goldze.mvvmhabit.utils.KLog;
import me.goldze.mvvmhabit.utils.StringUtils;
import me.goldze.mvvmhabit.utils.ToastUtils;

public class AuthBankViewModel extends AuthBaseViewModel {

    private String currentDictType;
    private List<DicInfoEntity> dicInfoList;
    private ImageInfoEntity imageInfo;


    public AuthBankViewModel(@NonNull Application application, DemoRepository model) {
        super(application, model);
        setTitleText(getString(R.string.auth_bank_card_page_title));
    }

    @Override
    public void onCreate() {
        super.onCreate();
        getSubmitedInfo(Constants.AUTH_PAGE_CODE_BANK_INFO_CODE);
//        getSubmitedBankInfo();
        getUserInfo();
    }


//    public void getSubmitedBankInfo() {
//        showDialog();
//        Map<String, Object> params = new HashMap<>();
//        model.getSubmitedBankInfo(params)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .subscribe(new Consumer<AuthBackResponse>() {
//                    @Override
//                    public void accept(AuthBackResponse response) throws Exception {
//
//                        dismissDialog();
//
//                        if (response == null || response.getData() == null)
//                            return;
//
//                        AuthBackResponse.DataBean bankInfo = response.getData();
//
//                        if (!StringUtils.isEmpty(bankInfo.getRealName())) {
//                            bankCardName.set(bankInfo.getRealName());
//
//                        }
//                        bankCardNum.set(bankInfo.getBankCard());
//                        bankName.set(new DicInfoEntity(bankInfo.getBankValue(), bankInfo.getBankCode()));
//
//                        List<AuthBackResponse.DataBean.BankCardImagesBean> bankCardImages = bankInfo.getBankCardImages();
//                        if (bankCardImages != null && bankCardImages.size() > 0) {
//
//                            idCardPositiveBean.set(bankCardImages.get(0));
//                        }
//                        KLog.i("upload img suc");
//                    }
//                }, new Consumer<Throwable>() {
//                    @Override
//                    public void accept(Throwable throwable) throws Exception {
//                        dismissDialog();
//                        KLog.e("upload fail:" + throwable.getMessage());
//                    }
//                });
//    }

    @Override
    protected void onSubmittedResponse(SubmitedAuthResponse response) {
        super.onSubmittedResponse(response);
        if (response == null || response.getData() == null || response.getData().getBankInfo() == null)
            return;

        SubmitedAuthResponse.DataBean.BankInfoBean bankInfo = response.getData().getBankInfo();

        if (!StringUtils.isEmpty(bankInfo.getRealName())) {
            bankCardName.set(bankInfo.getRealName());

        }
        bankCardNum.set(bankInfo.getBankCard());
        bankName.set(new DicInfoEntity(bankInfo.getBankCodeValue(), bankInfo.getBankCode()));

        List<AuthBackResponse.DataBean.BankCardImagesBean> bankCardImages = bankInfo.getBankCardImages();
        if (bankCardImages != null && bankCardImages.size() > 0) {

            AuthBackResponse.DataBean.BankCardImagesBean bankCardImagesBean = bankCardImages.get(0);
            idCardPositiveBean.set(bankCardImagesBean);
            imageInfo = new ImageInfoEntity();
            imageInfo.setFileType(bankCardImagesBean.getFileType());
            imageInfo.setImageName(bankCardImagesBean.getImageName());
            imageInfo.setImagePath(bankCardImagesBean.getImagePath());
            imageInfo.setImageUrl(bankCardImagesBean.getImageUrl());

        }

    }

    public void onItemSelected(String title, int position) {
        if (currentDictType == null || dicInfoList == null || position >= dicInfoList.size())
            return;
        bankName.set(dicInfoList.get(position));
    }

    public ObservableField<String> bankCardName = new ObservableField<>("");
    public ObservableField<String> bankCardNum = new ObservableField<>("");
    public ObservableField<DicInfoEntity> bankName = new ObservableField<>();
    public ObservableField<AuthBackResponse.DataBean.BankCardImagesBean> idCardPositiveBean = new ObservableField<>();
//    public ObservableField<SubmitedAuthResponse.DataBean.BankInfoBean> idCardPositiveBean = new ObservableField<>();


    public class UiChangeEvent {
        public SingleLiveEvent takePicEvent = new SingleLiveEvent();
        public SingleLiveEvent selectBankEvent = new SingleLiveEvent();
    }

    public UiChangeEvent uc = new UiChangeEvent();


    public BindingCommand clickUploadBankCard = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            uc.takePicEvent.setValue("");

        }
    });
    public BindingCommand bankNameClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {


            if (TextUtils.isEmpty(bankCardNum.get())) {

                ToastUtils.showShort(getString(R.string.auth_bank_input_bank_num));
                return;
            }
            getDictsBykey(DictInfoTypeKey.common_bankname);
        }
    });
    public BindingCommand onClickNextStep = new BindingCommand(new BindingAction() {
        @Override
        public void call() {

            if (imageInfo == null) {
                ToastUtils.showShort(getString(R.string.auth_pi_please_input_bank_card));
                return;
            }


            if (TextUtils.isEmpty(bankCardNum.get())) {
                ToastUtils.showShort(getString(R.string.auth_bank_input_bank_num));
                return;
            }
            if (bankName.get() == null || StringUtils.isEmpty(bankName.get().dictValue)) {
                ToastUtils.showShort(getString(R.string.auth_pi_please_input_bank_name_hint));
                return;
            }

            if (StringUtils.isEmpty(bankCardName.get())) {
                getUserInfo();
            } else {
                uploadBankInfo(bankCardName.get());
            }

        }
    });


    private void getUserInfo() {
        showDialog();
        Map<String, Object> maps = new HashMap<>();
        addSubscribe(model.getIdentityInfo(maps)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<IdentityInfoResponse>() {
                    @Override
                    public void accept(IdentityInfoResponse infoResponse) throws Exception {
                        dismissDialog();
                        if (infoResponse != null && infoResponse.getData() != null && !StringUtils.isEmpty(infoResponse.getData().realName)) {

                            bankCardName.set(infoResponse.getData().realName);
                        } else {
                            ToastUtils.showShort(infoResponse.getMessage());
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                }));


    }

    /**
     * 上传 银行卡信息
     * <p>
     * <p>
     * {
     * "authPageCode": "bank_info_code",    //银行卡认证code
     * "bankCode": "common_bankname_MANDIRI",   //银行名称字典code
     * "realName": "YOHANES PRASETYO",        //真实姓名 接口获取的不能手填
     * "userUuid": "20190423953",
     * "bankName": "MANDIRI",       //银行名称
     * "channel": "1",
     * "bankCard": "13655",
     * “isInformationWrong”:1   //如果是资料退回再次上传的 传1  要不是不传
     * "commonParam": 公参
     * }
     */
    private void uploadBankInfo(String realName) {
        showDialog();
        Map<String, Object> params = new HashMap<>();
        if (SPUtils.getInstance().getBoolean(SPKeys.SP_ISBACK)) {
            params.put("isInformationWrong", "1");

        }
        params.put("authPageCode", Constants.AUTH_PAGE_CODE_BANK_INFO_CODE);
        params.put("bankCode", bankName.get().dictCode);
        params.put("realName", realName);
        params.put("bankName", bankName.get().dictValue);
        params.put("bankCard", bankCardNum.get());

        List<ImageInfoEntity> bankCards = new ArrayList();
        bankCards.add(imageInfo);
        params.put("imageInfoParams", bankCards);

        model.saveOrUpdateBankList(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<RootApiBean>() {
                    @Override
                    public void accept(RootApiBean rootApiBean) throws Exception {

                        dismissDialog();
                        if (rootApiBean != null && rootApiBean.getStatus() == 200) {
                            AuthJumpManager.jumpToNextPage(Constants.AUTH_PAGE_CODE_BANK_INFO_CODE);
                            finish();

                        } else {
                            if (!TextUtils.isEmpty(rootApiBean.getMessage())) {
                                ToastUtils.showShort(rootApiBean.getMessage());
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });

    }


    public void getDictsBykey(final String dictType) {
        showDialog();
        Map<String, Object> dictParams = new HashMap<>();
        dictParams.put("dictType", dictType);
        model.getDicInfo(dictParams)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<DicInfoResponse>() {
                    @Override
                    public void accept(DicInfoResponse dicInfoResponse) throws Exception {
                        dismissDialog();
                        if (dicInfoResponse == null) return;

                        showPopWindow(dictType, dicInfoResponse.getData());


                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("error:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });

    }


    private void showPopWindow(String dictType, List<DicInfoEntity> data) {
        this.currentDictType = dictType;
        this.dicInfoList = data;
        uc.selectBankEvent.setValue("");

    }


    public String getCurrentDictType() {
        return this.currentDictType;
    }

    public List<DicInfoEntity> getCurrentDictList() {
        return this.dicInfoList;
    }

    public void doUploadImg(Uri imageUri, File imageFile, String fileType) {
        showDialog();
        Map<String, Object> params = new HashMap<>();
        params.put("userUuid", UUidUtils.getUUid());
        params.put("fileType", fileType);

        KLog.i("upload img start");

//        model.uploadImage(params, new File(imageUri.getPath()))
        model.uploadImage(params, imageFile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<UploadImageResponse>() {
                    @Override
                    public void accept(UploadImageResponse uploadImageResponse) throws Exception {

                        dismissDialog();
                        imageInfo = uploadImageResponse.getData().getImageInfo();

                        KLog.i("upload img suc");
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        dismissDialog();
                        KLog.e("upload fail:" + throwable.getMessage());
                        if (throwable instanceof ResultException) {
                            ToastUtils.showShort(throwable.getMessage());

                        }
                    }
                });
    }

}
